import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import './app-file-upload.less';
import { Environment } from '@/environments/environment';

@Component({})
export default class AppFileUpload extends Vue {

    /**
     * 表单数据
     */
    @Prop() public data!: string;

    @Watch('data', { immediate: true, deep: true })
    onDataChange(newval: any, val: any) {
        if (val) {
            let formData = JSON.parse(newval);
            let upload_arr: Array<string> = [];
            let export_arr: Array<string> = [];
            this.upload_keys.forEach((key: string) => {
                let _value = formData[key];
                if (!_value || Object.is(_value, '')) {
                    return;
                }
                upload_arr.push(`${key}=${_value}`);
            });
            this.export_keys.forEach((key: string) => {
                let _value = formData[key];
                if (!_value || Object.is(_value, '')) {
                    return;
                }
                export_arr.push(`${key}=${_value}`);
            });

            let uploadUrl: string = '/' + Environment.BaseUrl + Environment.UploadFile;
            let downloadUrl: string = '/' + Environment.BaseUrl + Environment.ExportFile;

            this.uploadUrl = `${uploadUrl}?${upload_arr.join('&')}&${this.custom_arr.join('&')}`;
            this.downloadUrl = `${downloadUrl}?${export_arr.join('&')}&${this.custom_arr.join('&')}`;

            this.files.forEach((file: any) => {
                file.url = this.downloadUrl.indexOf('?') !== -1 ? `${this.downloadUrl}&fileid=${file.id}` : `${this.downloadUrl}?fileid=${file.id}`;
            });
        }
    }

    /**
     * 已上传文件值
     */
    @Prop() value?: any;

    @Watch('value')
    onValueChange(newval: any, val: any) {
        if (newval) {
            this.files = JSON.parse(newval);
            this.files.forEach((file: any) => {
                file.url = this.downloadUrl + '?fileid=' + file.id;
            });
        } else {
            this.files = [];
        }
    }

    /**
     * 所属表单项名称
     */
    @Prop() name!: string;

    /**
     * 是否禁用
     */
    @Prop() disabled?: boolean;

    /**
     * 附加参数
     */
    public editorParams?: any;

    /**
     * 上传文件路径
     */
    public uploadUrl = '/' + Environment.BaseUrl + Environment.UploadFile;

    /**
     * 下载文件路径
     */
    public downloadUrl = '/' + Environment.BaseUrl + Environment.ExportFile;

    /**
     * 文件列表
     */
    public files = [];

    /**
     * 上传keys
     */
    public upload_keys: Array<any> =[];

    /**
     * 导出keys
     */
    public export_keys: Array<any> =[];

    /**
     * 自定义数组
     */
    public custom_arr: Array<any> =[];

    /**
     * 挂载回调
     */
    public mounted() {
        let form: any = JSON.parse(this.data);
        if (!form || !form[this.name]) {
            return;
        }
        this.editorParams = form[this.name].editorParams;
        if (!this.editorParams || Object.keys(this.editorParams).length === 0) {
            return;
        }
        let editorParams: any = {};
        let uploadparams: string = '';
        let exportparams: string = '';
        Object.assign(editorParams, this.editorParams);
        if (editorParams.uploadparams && !Object.is(editorParams.uploadparams, '')) {
            uploadparams = editorParams.uploadparams;
        }
        if (editorParams.exportparams && !Object.is(editorParams.exportparams, '')) {
            exportparams = editorParams.exportparams;
        }
        let upload_keys: Array<string> = uploadparams.split(';');
        let export_keys: Array<string> = exportparams.split(';');
        let custom_arr: Array<string> = [];
        if (editorParams.customparams && !Object.is(editorParams.customparams, '')) {
            Object.keys(editorParams.customparams).forEach((name: string) => {
                if (editorParams.customparams[name]) {
                    custom_arr.push(`${name}=${editorParams.customparams[name]}`);
                }
            });
        }
        this.upload_keys = upload_keys;
        this.export_keys = export_keys;
        this.custom_arr = custom_arr;
    }

    /**
     * 上传之前
     */
    public beforeUpload(file: any) {
        console.log('上传之前');
    }

    /**
     * 上传成功回调
     */
    public onSuccess(response: any, file: any, fileList: any) {
        let arr: Array<any> = [];
        arr = [...response.files];
        this.files.forEach((f: any) => {
            arr.push({ name: f.name, id: f.id });
        });
        let value: String = arr.length > 0 ? JSON.stringify(arr) : '';
        this.$emit('change', value);
    }

    /**
     * 上传失败回调
     */
    public onError(error: any, file: any, fileList: any) {
        this.$Notice.error({ title: '上传失败' });
    }

    /**
     * 移除文件
     */
    public onRemove(file:any, fileList:any) {
        let arr: Array<any> = [];
        fileList.forEach((f:any) => {
            if (f.id != file.id) {
                arr.push({ name: f.name, id: f.id });
            }
        });
        let value: String = arr.length > 0 ? JSON.stringify(arr) : '';
        this.$emit('change', value);
    }

    /**
     * 下载文件
     */
    public onDownload(file:any) {
        window.open(file.url);
    }

    /**
     * 渲染组件 
     */
    public render() {
        return (<div>
            <el-upload disabled={this.disabled} file-list={this.files} action={this.uploadUrl} before-upload={this.beforeUpload} on-success={this.onSuccess} on-error={this.onError} before-remove={this.onRemove} on-preview={this.onDownload}>
                <el-button size="small" icon="el-icon-upload">上传</el-button>
            </el-upload>
        </div >);
    }

}